package org.zjt.agent.convertor;

import lombok.extern.slf4j.Slf4j;
import org.zjt.agent.ClassDefineDescription;
import org.zjt.agent.Order;
import org.zjt.agent.generate.ByteCodeGenerator;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Objects;
import java.util.Optional;
import java.util.logging.Logger;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-07-04 下午10:49
 * @see
 */
@Slf4j
public class RedefineClassConverter implements ClassConverter<ClassDefineDescription> {



    private final ByteCodeGenerator byteCodeGenerate;

    public RedefineClassConverter(ByteCodeGenerator byteCodeGenerate) {
        this.byteCodeGenerate = byteCodeGenerate;
    }

    @Override
    public Optional<byte[]> convert(ClassDefineDescription classDefine) {
        Optional<byte[]> generate = byteCodeGenerate.generate(classDefine);
        //log.info("classDefine:{}\t generateClass:{}",classDefine.getClassName(),generate.isPresent());
        if (!generate.isPresent())
            return generate;
        byte[] bytes = generate.get();
        saveClassConstruct(bytes,classDefine);
        return Optional.of(bytes);
    }



    public void saveClassConstruct(byte[] bytes,ClassDefineDescription classDefine) {
        String fileName = "/Users/juntao.zhang/dev/workspace/myproject/java-agent/java-agent-demo/src/main/java/org/zjt/agent/generate/" + classDefine.getClassName() + ".class";
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(fileName, "rw");
             FileChannel fileChannel = randomAccessFile.getChannel();) {
            fileChannel.write(ByteBuffer.wrap(bytes));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
